package jp.eisbahn.eclipse.plugins.lingrclipse.view;

import java.util.List;

import jp.eisbahn.eclipse.plugins.lingrclipse.LingrOccupant;

import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.widgets.Control;

public class OccupantListContentProvider implements IStructuredContentProvider, OccupantListener {
	
	private TableViewer tableViewer;

	public Object[] getElements(Object inputElement) {
		return ((OccupantList)inputElement).getCurrentOccupantList().toArray();
	}

	public void dispose() {
	}

	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		tableViewer = (TableViewer)viewer;
		if (oldInput != null) {
			((OccupantList)oldInput).removeOccupantListener(this);
		}
		if (newInput != null) {
			((OccupantList)newInput).addOccupantListener(this);
		}
	}

	public void occupantChanged(
			final List<LingrOccupant> oldOccupantList, final List<LingrOccupant> newOccupantList) {
		if (tableViewer != null) {
			Control control = tableViewer.getControl();
			if ((control != null) && !(control.isDisposed())) {
				control.getDisplay().syncExec(new Runnable() {
					public void run() {
						for (LingrOccupant occupant : oldOccupantList) {
							tableViewer.remove(occupant);
						}
						for (LingrOccupant occupant : newOccupantList) {
							tableViewer.add(occupant);
						}
					}
				});
			}
		}
	}

}
